package com.tian.util;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-05-14 0:35
 * {@code @version:} 1.0
 */
public class CodeConvert {
    public static void main(String[] args) {
        String originalString = "CHARGE_NO100000"; // 包含数字和字母的原始字符串

        // 将字符串转换为十进制再转换为BCD码
        byte[] bcdBytes = strToBcd(originalString);

        // 将BCD码转换为十进制再转换为字符串
        String newString = bcdToStr(bcdBytes);
        System.out.println("BCD to String: " + newString);
    }
    public static byte[] strToBcd(String str) {
        if (str == null || str.equals("")) {
            return new byte[0];
        }
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length(); i += 2) {
            String temp = str.substring(i, i + 2);
            bytes[i / 2] = (byte) ((Character.digit(temp.charAt(0), 16) << 4) + Character.digit(temp.charAt(1), 16));
        }
        return bytes;
    }
    public static String bcdToStr(byte[] bytes) {
        char[] temp = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            temp[i * 2] = (char) (((bytes[i] & 0xf0) >> 4) + '0');
            if (temp[i * 2] > '9') {
                temp[i * 2] = (char) ((temp[i * 2] - '0') - 10 + 'A');
            }
            temp[i * 2 + 1] = (char) ((bytes[i] & 0x0f) + '0');
            if (temp[i * 2 + 1] > '9') {
                temp[i * 2 + 1] = (char) ((temp[i * 2 + 1] - '0') - 10 + 'A');
            }
        }
        return new String(temp);
    }
}
